<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding-right: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="customerId"
                label="客户名称"
                :rules="[{ required: true, message: '请选择客户名称' }]"
                :validate-trigger="['change', 'blur']"
              >
                <ASelect
                  v-model="form.customerId"
                  placeholder="输入客户名称进行搜索"
                  allow-clear
                  allow-search
                  allow-create
                >
                  <AOption
                    v-for="(item, index) in companyList"
                    :key="index"
                    :label="item.customerName"
                    :value="item.customerId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="isInclTax" label="含税">
                <ASelect v-model="form.isInclTax" placeholder="是否含税" allow-search>
                  <AOption label="是" :value="1"></AOption>
                  <AOption label="否" :value="0"></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="deliveryMethod" label="送货方式">
                <ASelect
                  v-model="form.deliveryMethod"
                  allow-clear
                  placeholder="请选择送货方式"
                  allow-search
                >
                  <AOption label="包送" value="包送"></AOption>
                  <AOption label="自提" value="自提"></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="paymentMethod" label="结算方式">
                <AInput v-model="form.paymentMethod" allow-clear placeholder="请输入结算方式" />
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem :content-flex="false" field="detailList" :hide-label="true">
                <ACard
                  v-for="(item, index) in form.detailList"
                  :key="index"
                  size="small"
                  class="card-container"
                >
                  <template #extra>
                    <ALink @click="editProduct('add')">增加产品</ALink>
                    <ALink v-if="form.detailList.length > 1" @click="editProduct('del', index)">
                      删除产品
                    </ALink>
                  </template>
                  <ARow :gutter="10">
                    <ACol :span="12">
                      <AFormItem
                        :field="`detailList[${index}].productId`"
                        label="产品名称"
                        :rules="[{ required: true, message: '请输入产品名称' }]"
                        :validate-trigger="['change', 'input', 'blur']"
                      >
                        <ASelect
                          v-model="item.productId"
                          v-model:input-value="productSearch"
                          allow-search
                          placeholder="请选择产品名称"
                          :trigger-props="{ contentStyle: { width: 'max-content' } }"
                          :filter-option="proFilter"
                          @change="editProduct('change', index)"
                        >
                          <template #empty>
                            <div style="padding: 6px 12px">
                              <ALink :hoverable="false" @click="openAdd()"> 新增产品 </ALink>
                            </div>
                          </template>

                          <AOption
                            v-for="(item, index) in productList"
                            :key="index"
                            :label="item.productName"
                            :value="`${item.productId}-${item.specModel}`"
                            :disabled="detailIds.includes(`${item.productId}-${item.specModel}`)"
                          >
                            <div class="w100 erp-row-center-between">
                              <div>{{ item.productName }}</div>
                              <ATag v-if="item.specModel" color="blue">
                                {{ item.specModel }}
                              </ATag>
                            </div>
                          </AOption>
                        </ASelect>
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="specModel" label="规格型号">
                        {{ item.specModel }}
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="unit" label="单位">
                        {{ item.unit }}
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="unitPrice" label="单价">
                        <AInputNumber
                          v-model="item.unitPrice"
                          model-event="input"
                          placeholder="请输入单价"
                          :precision="4"
                          :step="1"
                          hide-button
                        />
                      </AFormItem>
                    </ACol>
                  </ARow>
                </ACard>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="备注" class="erp-mt-10">
                <ATextarea v-model="form.remark" placeholder="请输入备注" />
              </AFormItem>
            </ACol>
          </ARow>
        </AForm>
      </AScrollbar>
    </AModal>
    <addProduct
      v-model:visible="addProductVisible"
      title="新增产品"
      :check-data="{ productName: productSearch }"
      @reload="getProductList"
    ></addProduct>
  </div>
</template>

<script lang="ts" setup>
import { Message, Modal, SelectOptionData } from '@arco-design/web-vue'
import { CustomerResItem, editCustomer, getCustomerAllList } from '@renderer/api/company'
import {
  editQuotation,
  getProductAllList,
  getQuotationDetail,
  ProductResItem,
  QuotationReq,
  QuotationResItem
} from '@renderer/api/salesDep'
import { useMenuState } from '@renderer/store'
import { deleteNullObject } from '@renderer/utils/data-processing'
import addProduct from '@renderer/views/Information/ProductInfo/editPopupForm.vue'

interface Props {
  [key: string]: any
  checkData?: Partial<QuotationResItem>
  fromModule?: string
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  },
  fromModule: 'quotation'
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const detailIds = computed(() => form.value.detailList.map((item) => item.productId))
const form = ref<QuotationReq>({
  isInclTax: 1,
  customerId: '',
  deliveryMethod: '',
  paymentMethod: '',
  remark: '',
  detailList: [
    {
      productId: '',
      specModel: '',
      unitPrice: 0,
      unit: ''
    }
  ]
})
const companyList = ref<CustomerResItem[]>([])
const productList = ref<ProductResItem[]>([])
const menuParam = useMenuState()
const productSearch = ref('')
const addProductVisible = ref(false)

// 获取客户列表
const getCompanyList = () => {
  getCustomerAllList({
    customerName: '',
    taxNo: '',
    contactName: ''
  }).then((res) => {
    companyList.value = res.data.list
  })
}
// 获取产品列表
const getProductList = () => {
  getProductAllList({ productType: 0 }).then((res) => {
    productList.value = res.data.list
  })
}
// 获取详情
const getDetail = () => {
  getQuotationDetail({ quotationOrderId: props.checkData.quotationOrderId! }).then((res) => {
    res.data.detailList.map((item) => {
      item.productId = `${item.productId}-${item.specModel}`
    })
    form.value = res.data
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          if (['新增', '复制'].includes(attrs.title as string)) {
            form.value.quotationOrderId = undefined
          }
          const temp = companyList.value.find((item) => item.customerId === form.value.customerId)
          form.value.detailList.map((item) => {
            item.productId = item.productId.split('-')[0]
            return item
          })
          if (!temp) {
            Modal.warning({
              title: '警告',
              content: '当前客户不存在，是否新增当前客户？',
              okText: '确认',
              cancelText: '取消',
              simple: false,
              hideCancel: false,
              maskClosable: false,
              closable: false,
              onOk: () => {
                editCustomer({ customerName: form.value.customerId }).then((res) => {
                  editQuotation(
                    deleteNullObject({ ...form.value, customerId: res.data as string })
                  ).then(() => {
                    Message.success(
                      ['新增', '复制'].includes(attrs.title as string) ? '新增成功' : '修改成功'
                    )
                    modalEvent('cancel')
                    emit('reload')
                  })
                })
              },
              onCancel: () => {}
            })
          } else {
            editQuotation(deleteNullObject(form.value)).then(() => {
              Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
              modalEvent('cancel')
              emit('reload')
            })
          }
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        isInclTax: 1,
        customerId: '',
        deliveryMethod: '',
        paymentMethod: '',
        remark: '',
        detailList: [
          {
            productId: '',
            specModel: '',
            unitPrice: 0,
            unit: ''
          }
        ]
      }
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      if (['修改', '复制'].includes(attrs.title as string)) {
        getDetail()
      }
      getCompanyList()
      getProductList()
      if ((attrs.title as string).includes('新增') && props.fromModule != 'quotation') {
        Object.assign(form.value, props.checkData)
      }
      break
    case 'cancel':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    default:
      break
  }
}

const editProduct = (type: 'add' | 'del' | 'change', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        productId: '',
        specModel: '',
        unitPrice: 0,
        unit: ''
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break
    case 'change':
      {
        const selectItem = productList.value.find(
          (item) =>
            `${item.productId}-${item.specModel}` === form.value.detailList[index!].productId
        )
        if (selectItem) {
          form.value.detailList[index!].specModel = selectItem.specModel!
          form.value.detailList[index!].unit = selectItem.unit!
        }
      }
      break
    default:
      break
  }
}

// 新增产品
const openAdd = () => {
  addProductVisible.value = true
}

const proFilter = (inputValue: string, option: SelectOptionData) => {
  return (
    (option.value as string)?.split('-')[1].includes(inputValue) ||
    option.label?.includes(inputValue)
  )
}
</script>
<style scoped lang="less">
.card-container + .card-container {
  margin-top: 10px;
}
:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
